<% layout('/layouts/default.html', {title: '指标展示提交',  libs: ['layout', 'dataGrid','validate','fileupload','inputmask']}){ %>
<div class="main-content" xmlns="http://www.w3.org/1999/html">
    <form id="inputForm" class="form-horizontal">
    <div class="box box-main">
        <div class="box-body" >
        <div style="float: right;">
            <button type="button" id="addDataGridRowBtn" class="btn btn-sm btn-primary btnList"><i class="fa fa-plus"></i> ${text('新增指标')} </button>&nbsp;&nbsp;
            <button type="button" class="btn btn-sm btn-primary" id="btnPassed" onclick="auditPassed()"><i class="fa fa-check"></i> ${text('审核通过')}</button>&nbsp;&nbsp;
            <button type="button" class="btn btn-sm btn-primary " id="btnBack" onclick="auditNoPassed()"><i class="fa fa-reply-all"></i> ${text('退 回')}</button>
            <button style="display: none" type="button" class="btn btn-sm btn-primary btnList" id="chuiBan" onclick="urgeHandle()"><i class="fa fa-check"></i> ${text('催 办')}</button>
        </div>
    </div>

        <div class="box-header">
            <#form:form id="searchForm" model="${dcSupExamQuotaInfo}" action="${ctx}/targetAudit/dcSupExamZBData?quotaGroup=${quotaGroup}" method="post" class="form-inline"
            data-page-no="${parameter.pageNo}" data-page-size="${parameter.pageSize}" data-order-by="${parameter.orderBy}">
            <#form:hidden path="examOrgList"/>
            <#form:hidden path="submitStatus"/>
            <#form:hidden path="examYear"/>
            </#form:form>
        </div>
    </form>
    <div class="box-body">
        <div id="guanjian" style="padding-bottom: 8px"><span style ="text-decoration:underline;font-size: 20px;color: #30bbbb">关键考核指标</span></div>
        <table id="dataGrid"></table>
    </div>
    <div class="box-body">
       <!-- <a href="javascript:void(0)" id="addDataGridRowBtn" class="btn btn-primary btn-sm mt10 mb10"><i class="fa fa-plus"></i> 新增指标</a>-->
        <a href="javascript:void(0)" id="GridAddRowBtn"   style="display: none"></i> 新增指标</a>
        <table id="addOrRemoveGrid"></table>
    </div>
    <div class="box-body">

        <div class="row">
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="control-label col-sm-4" title="">
                        <span class="required hide">*</span> ${text('联系人')}：<i class="fa icon-question hide"></i></label>
                    <label class="control-label-left col-sm-8" id="contactName">${dcSupExamQuota.contactName}</label>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="control-label col-sm-4" title="">
                        <span class="required hide">*</span> ${text('联系人电话')}：<i class="fa icon-question hide"></i></label>
                    <label class="control-label-left col-sm-8" id="contactPhone">${dcSupExamQuota.contactPhone}</label>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="control-label col-sm-2" title="">
                        <span class="required hide">*</span> ${text('附件')}：<i class="fa icon-question hide"></i></label>
                    <label class="control-label-left col-sm-10">
                        <#form:fileupload id="uploadFile" bizKey="${dcSupExamQuota.id}" bizType="dcSupExamQuota_file"
                        uploadType="all"  class="" readonly="true" preview="true"/>
                    </label>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="control-label col-sm-2">
                        <span class="required hide">*</span></label>
                    <div class="col-sm-10">
                        <button class="btn btn-primary btn-sm" type="button" style="font-size: 14px"  id="batch">批量下载</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
</div>
<% } %>
<script>
    var examYear = '${dcSupExamQuota.examYear}';
    var examId = '${dcSupExamQuota.examId}';
    var noticeId = '${dcSupExamQuota.noticeId}';
    var exameOrg = '${dcSupExamQuota.createOrg}';
    var submitStatus = '${dcSupExamQuota.submitStatus}';
    var contactName = '${dcSupExamQuota.contactName}';
    var contactPhone = '${dcSupExamQuota.contactPhone}';
    var examTitle = '${dcSupExamQuota.examTitle}';
    var auditStatus = '${auditStatus}';
    var quotaGroup = '${quotaGroup}';
    var exameOrgDataList = [];

     if(submitStatus == '1'){
         $("#btnPassed").css("display","none");
         $("#btnBack").css("display","none");
         $("#addDataGridRowBtn").css("display","none");
         //催办按钮
         $("#chuiBan").css("display","block");
     }else if(submitStatus == '4'){
         //审核通过按钮
         $("#btnPassed").css("display","none");
         //退回按钮
         $("#btnBack").css("display","none");
         //催办按钮
         $("#chuiBan").addClass("disabled");
         //新增指标按钮
         $("#addDataGridRowBtn").css("display","none");
     } else if(submitStatus == '3'){
         //审核通过按钮
         $("#btnPassed").css("display","none");
         //退回按钮
         $("#btnBack").css("display","none");
         //新增指标按钮
         $("#addDataGridRowBtn").css("display","none");
     }else if(submitStatus == '0'){
         //催办按钮
         $("#chuiBan").css("display","block");
     }
    //审核退回
    function auditNoPassed() {
        //子页面接收父页面传过来的数据
        //var exameOrgs = $("#examOrgList").val();
        if (hasDisabled($("#btnBack"))){
            return;
        }
        let exameOrgs =  '${dcSupExamQuota.examOrgList}';
        js.confirm("您确定要退回【"+examTitle+"】关键报送的指标吗？该操作不可恢复！", {
            url: '${ctx}/targetAudit/exameSendBack',
            data: {createOrg:exameOrg,examId:examId,quotaGroup:quotaGroup},
            callback: function(data){
                window.parent.orgChange(exameOrg,'3');
            },
            dataType: 'json',
            async: false, message: '正在退回...',
            shadeClose: true }
        );
    }

    //催办功能
    // function urgeHandle() {
    //     var createOrg = `${dcSupExamQuota.createOrg}`;
    //     var createOrgName =`${dcSupExamQuota.createOrgName}`;
    //     js.confirm("是否催办关键报送指标111？", {
    //         url: '${ctx}/targetAudit/urgeInformation',
    //         data: {
    //             "createOrg":createOrg,
    //             "remarks":"关键指标",
    //             "examTitle":examTitle,
    //         },
    //         callback: function(data){
    //             js.showMessage(data.message);
    //         },
    //         dataType: 'json',
    //         async: false, message: '正在催办...',
    //         shadeClose: true });
    // }
    function urgeHandle(){
        js.loading();
        js.layer.open({
            type: 2,
            title: ['催办'],
            area: ['800px', '400px'],
            scrollbar: true,
            shadeClose: false,
            content: "${ctx}/targetAudit/cuibanPageGJ?id=${dcSupExamQuota.examId}&org=${dcSupExamQuota.createOrg}",
            btn1: function (index, layero) {
            },
            success: function (data) {
                js.closeLoading(0, true);
            },
            end:function () {

            }
        });
    }

    var column_ =[
        // {header:'${text("序号")}', name:'rowno', width:30, align:"center"},
        /*{header:'${text("主键")}', name:'id', hidden:true},*/
        {header:'${text("年度")}', name:'examYear', index:'a.exam_year', width:80, align:"center",hidden:true,formatter: function(val, obj, row, act){
                return examYear;
            }},
        {header:'${text("组织类别")}',hidden:true, name:'orgTyoe', width:30, align:"center"},
        {header:'${text("类别")}', name:'quotaType', width:80, align:"center",
            formatter: function(val, obj, row, act){
                return js.getDictLabel(${@DictUtils.getDictListJson('dc_quotaType_guanjian')},
                    val, '${text("未知")}', true);
            },
            unformat: function(val, obj, cell){
                return val;
            },
            editable:true, edittype:'select', editoptions:{'class':'form-control required gj',
                items: $.merge([], ${@DictUtils.getDictListJson('dc_quotaType_guanjian')}),
                itemLabel: 'dictLabel', itemValue: 'dictValue', dataInit: function(element){
                    $(element).select2().on("change",function(){$(this).resetValid()});
                }
            },
            unformat: function(val, obj, cell){
                return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();
            }
        },
        {header:'${text("序号")}', name:'sortNum', index:'a.sort_num', width:30, align:"center",editable:true,edittype:'text', editoptions:{'class':'form-control digits gj',
                dataInit: function(element){
                    $(element).on("keyup",function(){
                        $('#'+element.id).val($('#'+element.id).val().replace(/\D|^0/g,''));
                    });
                }
                },
                unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}},
        {header:'${text("指标分类")}', name:'quotaClass', width:50, align:"center", hidden:true},
        {header:'${text("目标内容")}', name:'quotaContent', index:'a.quota_content', width:200, align:"left",
            editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control required cont gj'}, unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}},
        {header:'${text("单位")}', name:'quotaUnit', index:'a.quota_unit', width:30, align:"center",
            editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control'}, unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}},
        {header: "权数",name: 'quotaWeight',edittype:'text',editable:true,width: 30,align: 'center',editoptions:{'maxlength':'11', 'class':'form-control required gj',
                dataInit: function(element){
                    $(element).on("keyup",function(){
                        $('#'+element.id).val($('#'+element.id).val().replace(/[^\d.]/g,""));
                        $('#'+element.id).val($('#'+element.id).val().replace(/^\./g,""));
                        $('#'+element.id).val($('#'+element.id).val().replace(/\.{2,}/g,"."))
                        $('#'+element.id).val($('#'+element.id).val().replace(".","$#$").replace(/\./g,"").replace("$#$","."))
                        $('#'+element.id).val($('#'+element.id).val().replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'));
                        refreshZpCount();
                    });
                }},
                unformat: function(val, obj, cell){
                    return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();
                },
                formatter: function(val, obj, row, act){
                    if(val==null){
                        val=0;
                    }
                    var wg=parseFloat(val).toFixed(2);
                    return wg;
                }
        },
        {header:'${text("本年度目标")}', name:'currentYaerGoal', index:'a.current_yaer_goal', width:50, align:"center",
            editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control required gj'}, unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}},
        {header:'${text("考核方式")}', name:'assessMethod', index:'a.assessMethod', width:80, align:"center",
            editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control'},
            formatter: function(val, obj, row, act){
                return js.getDictLabel(${@DictUtils.getDictListJson('dc_exam_assessment')},
                    val, '${text("")}', true);
            },
            editable:true, edittype:'select', editoptions:{'class':'form-control gj',
                items: $.merge([{dictLabel:'&nbsp;',dictValue:''}], ${@DictUtils.getDictListJson('dc_exam_assessment')}),
                itemLabel: 'dictLabel', itemValue: 'dictValue', dataInit: function(element){
                    $(element).select2().on("change",function(){$(this).resetValid()});
                }
            },
            unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}},
        {header:'${text("上一年度目标任务")}', name:'lastYaerGoal', index:'a.last_yaer_goal', width:50, align:"center",
            editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control'},unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}},
        {header:'${text("上一年度完成情况")}', name:'lastYearComplete', index:'a.last_year_complete', width:50, align:"center",
            editable:true, edittype:'text', editoptions:{'class':'form-control'}, unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}},
        {header:'${text("备注")}', name:'remarks', index:'a.remarks', width:50, align:"center",
            editable:true, edittype:'text', editoptions:{'maxlength':'200', 'class':'form-control'},
            formatter: function(val, obj, row, act){
                return js.getDictLabel(${@DictUtils.getDictListJson('dc_exam_remarks')},
                    val, '${text("未知")}', true);
            },
            editable:true, edittype:'select', editoptions:{'class':'form-control required gj',
                items: $.merge([], ${@DictUtils.getDictListJson('dc_exam_remarks')}),
                itemLabel: 'dictLabel', itemValue: 'dictValue', dataInit: function(element){
                    $(element).select2().on("change",function(){$(this).resetValid()});
                }
            },
            unformat: function(val, obj, cell){return $('#'+obj.rowId+'_'+obj.colModel.name, cell).val();}},
        {header:'${text("被考核单位")}', name:'exameOrg',width:130, align:"center",title:false,hidden:true,
                formatter: function(val, obj, row, act){
                    return js.val(row, 'exameOrg')+'|'+js.val(row, 'exameOrgNames');
                },
                unformat: function(val, obj, cell){
                    var str = cell.childElementCount;
                    if (cell.childElementCount > 0) {
                        var exameOrgCode= $('#office_'+obj.rowId+'_exameOrgCode', cell).val();
                        var exameOrgName= $('#office_'+obj.rowId+'_exameOrgName', cell).val();
                        return exameOrgCode + '|' + exameOrgName;
                    }
                    return cell.outerText;
                },
                editable: true, edittype: "custom", editoptions: {
                    custom_element: function(val, editOptions) {
                        if (val.split('|')[0] == "undefined" && val.split('|')[1] == "undefined") {
                            val = "|"
                        }
                        return js.template('treeselectTpl', {
                            id:'office_'+editOptions.id,  title: '被考核单位',type:"text",
                            name: 'exameOrgCode', value: val.split('|')[0],
                            labelName: 'exameOrgName', labelValue: val.split('|')[1],
                            //labelValue:"${officeName!}", labelName:"exameOrgNames",
                            url: '${ctx}/sys/office/treeUnitData', cssClass: ''
                        });
                    }
                }
        },
        {header:'操作', name:'actions', width:60, sortable:false, fixed:true, formatter: function(val, obj, row, act){
                    var actions = [];
                    actions.push('<a href="#" onclick="js.confirm(\'你确认要删除这条数据吗？\', function(){$(\'#dataGrid\').dataGrid(\'delRowData\',\''+obj.rowId+'\')});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');

                    return actions.join('');
                }
        }
    ];

    // 初始化DataGrid对象
    $(function () {
        searchData();
    })

    function searchData() {
        jQuery('#dataGrid').GridUnload();
       let option =  {
            // 查询数据表单
            data: ${toJson(dcSupExamQuotaInfoList)},
            editGridInitRowNum: 0,
                datatype: "local", // 设置本地数据
            showRownum: false,
            // 设置数据表格列
            columnModel: column_,
            showCheckbox:false,
            emptyDataHint: true,
            showFooter: true, // 是否显示底部合计行
            editGrid: true,				// 是否是编辑表格
            editGridAddRowBtn: $('#GridAddRowBtn'),	// 子表增行按钮
            editGridAddRowInitData: function (e){
            return addRowInitData;
        },	// 新增行的时候初始化的数据

            editGridInputFormListName: 'dcSupExamQuotaInfoList', // 提交的数据列表名
                editGridInputFormListAttrs: 'id,examYear,quotaType,sortNum,quotaClass,quotaContent,quotaUnit,quotaWeight,currentYaerGoal,lastYaerGoal,remarks,exameOrg,assessMethod,orgType',
            // 加载成功后执行事件
            ajaxSuccess: function (data) {
            if(data.records=='0'){
                //审核通过按钮
                $("#btnPassed").css("display","none");
                //退回按钮
                $("#btnBack").css("display","none");
                //新增指标按钮
                $("#addDataGridRowBtn").css("display","none");
            }
            if(submitStatus == '4' || submitStatus == '3'){
                $('#dataGrid').dataGrid('hideCol', 'actions');
            }
            js.closeMessage();
            //汇总
            refreshZpCount();
            window.parent.change(exameOrg,submitStatus);
        }
        }
        if (submitStatus == '4'){
            option.editGrid=false
        }else {
            option.editGrid=true
        }
        $('#dataGrid').dataGrid(option);
    }
    //总分
    function refreshZpCount(){
        let data = $('#dataGrid').dataGrid('getRowData');
        let allQuotaWeight=0;
        let allQuotaScore=0;
        for (let i = 0; i < data.length; i++) {
            allQuotaWeight+=parseFloat(data[i].quotaWeight||0);
        }
        $('#dataGrid').dataGrid("footerData", "set", {
            "quotaContent": "总分</span>",
            "quotaWeight": "<span>&nbsp;"+allQuotaWeight+" &nbsp;</span>"
        }, false);
    }
    //新增指标
    $('#addDataGridRowBtn').click(function (){
        if (hasDisabled(this)){
            return;
        }
        let allData =$('#dataGrid').dataGrid('getRowData');
        var len = allData.length+1;
        addRowInitData={examYear:examYear,examId:examId,exameOrg:exameOrg,quotaClass:'1',rowno:len};
        $('#GridAddRowBtn').click();
    })
    //判断按钮是否禁用
    function hasDisabled(dom){
        return  $(dom).hasClass("disabled");
    }

    //审核通过
    function auditPassed(){
                let datagrid=$('#dataGrid').dataGrid('getRowData');
                if(datagrid.length==0){
                    js.showMessage("未上报指标，无法审核通过");
                    return;
                }
                let hasValid=true;
                let html= $("#inputForm").find(".cont");
                var arr=new Array();
                for (let i = 0; i < html.length; i++) {
                    arr[i]=$(html[i]).val();
                }
                let set=new Set(arr);
                if(arr.length !=set.size){
                    js.showMessage("目标内容不能相同！");
                    // js.showErrorMessage("目标内容不能相同！");
                    return;
                }
                let inputs = $("#inputForm").find(".gj");
                for (let i = 0; i <inputs.length; i++) {
                   let has = $("#inputForm").validate().element(inputs[i]);
                    if (has==false){hasValid=false}
                }

                if (!hasValid){return;}

                let allData =$('#dataGrid').dataGrid('getRowData');
                let subData = {"dcSupExamSumQuotaDtoListStr":JSON.stringify(allData),
                    "id":'${dcSupExamQuota.id}',
                    "noticeId":noticeId,
                    "examId":examId,
                    "contactName":contactName,
                    "contactPhone":contactPhone,
                    "examYear":examYear,
                    "fileUploadIds":$("#uploadFile").val(),
                    "typeIndex":2,
                    "createOrg":'${dcSupExamQuota.createOrg}',
                    "createOrgName":'${dcSupExamQuota.createOrgName}',
                    "quotaGroup":'${quotaGroup}'
                };

                js.confirm("您确定要审核通过吗？该操作不可恢复！", {
                    url: '${ctx}/targetAudit/saveAuditIndex',
                    data: subData,
                    callback: function(data){
                        if (data.result=="true"){
                            //审核通过按钮
                            $("#btnPassed").css("display","none");
                            //退回按钮
                            $("#btnBack").css("display","none");
                            //催办按钮
                            $("#chuiBan").addClass("disabled");
                            //新增指标按钮
                            $("#addDataGridRowBtn").css("display","none");
                            $('#dataGrid').dataGrid('hideCol', 'actions');
                            js.showMessage(data.message);
                            var params ={
                                "quotaGroup":'${quotaGroup}',
                                "examId":examId,
                                "createOrg":'${dcSupExamQuota.createOrg}',
                                "submitStatus":'4',
                                "examYear":examYear
                            };
                            window.parent.orgChange(exameOrg,'4');
                            }else {
                                js.showMessage(data.message);
                            }
                    },
                    dataType: 'json',
                    async: false, message: '正在提交...',
                    shadeClose: true }
                );


    }

</script>
<!--文件下载-->
<script>
    $("#batch").click(function (){
        var list=	$("#uploadFile").val();
        if (list == null || list == ''){
            js.showMessage("下载列表为空");
            return;
        }
        var id=	'${dcSupExamQuota.id}';
        var bizType='dcSupExamQuota_file';
        let xhr = new XMLHttpRequest();
        xhr.open('GET', "${ctx}/taskdeploy/dcSupTaskInfo/queryDownLoadDocument?id="+id+'&bizType='+bizType+"&jpgId="+list, true);
        xhr.setRequestHeader('Content-Type', `application/json`);
        xhr.responseType = 'blob';
        let that = this;
        xhr.onload = function () {
            if (this.status == 200) {
                //接受二进制文件流
                var blob = this.response;
                let downloadElement = document.createElement('a');
                let href = blob;
                if (typeof blob == 'string') {
                    downloadElement.target = '_blank';
                } else {
                    href = window.URL.createObjectURL(blob) ;//创建下载的链接
                }
                downloadElement.href = href;
                //下载后文件名
                var dateName=getNowTime();
                downloadElement.download =   "关键指标_"+dateName+".zip";
                document.body.appendChild(downloadElement)
                downloadElement.click(); //点击下载
                document.body.removeChild(downloadElement); //下载完成移除元素
                if (typeof blob != 'string') {
                    window.URL.revokeObjectURL(href); //释放掉blob对象
                }
            }else{
                js.showMessage("文件导出失败");
            }
        }
        xhr.send();
    })

    // 获取当前时间
    function getNowTime() {
        const yy = new Date().getFullYear()
        const MM = (new Date().getMonth() + 1) < 10 ? '0' + (new Date().getMonth() + 1) : (new Date().getMonth() + 1)
        const dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
        const HH = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()
        const mm = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
        const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
        return yy+MM+ dd+HH+mm+ss
    }

</script>
<style>
    .ui-jqgrid-bdiv {
        max-height: 400px;
    }
    #jqgh_addDataGrid_rn{
        display: none;
    }
</style>